package rxjava.application.com.androidmyp.Data;


import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;

/**
 * Created by Administrator on 2016/4/14.
 */
public class ApiManger {
    private static ApiManger apiManger;

    public static ApiManger getIntance() {
        synchronized (ApiManger.class) {
            if (apiManger == null) {
                apiManger = new ApiManger();
            }
        }
        return apiManger;
    }

    public ApiCenter api;

    public ApiManger() {
        OkHttpClient okHttp = new OkHttpClient();
        okHttp.interceptors().add(new LoggingInterceptor());
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl("http://172.16.1.174");
        builder.addConverterFactory(GsonConverterFactory.create());
        builder.addCallAdapterFactory(RxJavaCallAdapterFactory.create());
        builder.client(okHttp);
        Retrofit restAdapter = builder.build();
        api = restAdapter.create(ApiCenter.class);
    }

    /**
     * Retrofit2.0已经把网络部分剥离了，所以需要自己实现Log
     */
    static class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();
            System.out.println(
                    String.format("Sending request %s on %s%n%s", request.url(), chain.connection(),
                            request.headers()));
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
            System.out.println(
                    String.format("Received response for %s in %.1fms%n%s", response.request().url(),
                            (t2 - t1) / 1e6d, response.headers()) + response.message() + response.body() + response.request().toString());
            return response;
        }
    }
}
